const http = require("http");
const fs = require("fs");
const url = require("url");
const qs = require("querystring");

http.createServer((req,res)=>{
    const pn = url.parse(req.url).pathname;
    // 服务器的根路由
    if(pn.includes("/api")){
        dataHandle(req,res);            //走数据处理
    }else{
        staticHandle(req,res);          //走静态处理函数
    }
}).listen(3000,()=>{
    console.log("服务器开启成功：http://localhost:3000")
})

// 处理的函数区域
function dataHandle(req,res){
    if(req.method === "GET"){
        const obj = url.parse(req.url, true).query;
        programHandle(req, res, obj);
    }else if(req.method === "POST"){
        let str = "";
        req.on("data",(d)=>{
            str += d;
        })
        req.on("end",()=>{
            const obj = qs.parse(str);
            programHandle(req, res, obj);
        })
    }
}
function staticHandle(req,res){
    const pn = url.parse(req.url).pathname
    fs.readFile("./www" + pn, (err,data)=>{
        if(err){
            res.write("Forbidden \n You don't have permission to access this resource.")
        }else{
            res.write(data);
        }
        res.end();
    })
}

// 功能函数
function programHandle(req, res, data){
    // 功能路由
    // 接收到数据之后，根据数据中携带的功能类型，决定执行那个具体的功能
    switch(data.type){
        case "getBanner":
            getBanner(req, res, data);
            break;
        case "login":
            login(req, res, data);
            break;
        case "register":
            register(req, res, data);
            break;
        default:
            error(req, res, data);
    }
}

function getBanner(req, res, data){
    // 服务器先读取banner数据
    fs.readFile("./database/banner.json","utf-8",(err,data)=>{
        const obj = {};
        if(err){
            obj.code = 0;
            obj.title = "数据查找失败";
            obj.data = [];
        }else{
            obj.code = 1;
            obj.title = "数据查找成功";
         
            obj.data = JSON.parse(data);
        }
        res.end();
    });
}
// 以下函数可有可无
function login(req, res, data){
    res.write("login")
    res.end();
}
function register(req, res, data){
    res.write("register")
    res.end();
}
function error(req, res, data){
    res.write("Forbidden \n You don't have permission to access this resource.");
    res.end();
}